#include "jsonutils.h"

#include <QFile>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDir>


JsonUtils::JsonUtils(QObject *parent)
    : QObject{parent}
{}

void JsonUtils::saveJsonFile(QString fileName, QString key, QString value)
{
    // 将字符串转换为 QJsonDocument
    QJsonDocument jsonDocTmp = QJsonDocument::fromJson(value.toUtf8());

    // 检查是否转换成功
    if (jsonDocTmp.isNull()) {
        qDebug() << "Failed to create JSON document.";
        return;
    }

    // 将 QJsonDocument 转换为 QJsonObject
    QJsonObject jsonObjTmp = jsonDocTmp.object();

    if (!QFile::exists(fileName)) {
        qDebug() << "file not exist :" << fileName;
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::ReadWrite)) {
        qDebug() << "file not open :" << file.errorString();
        return;
    }
    QByteArray buf = file.readAll();


    QJsonDocument jsonDoc = QJsonDocument::fromJson(buf);
    if (jsonDoc.isNull()) {
        qDebug() << "无法解析json字符串";
        return;
    }
    if (!jsonDoc.isObject()) {
        qDebug() << "json file is not object";
        return;
    }

    QString newKey = key;
    QJsonObject jsonObject = jsonDoc.object();
    if (jsonObject.contains(newKey)) {
        int id = newKey.mid(6).toInt();
        id++;
        while (jsonObject.contains("button" + QString::number(id))) {
            id++;
        }
        newKey = "button" + QString::number(id);

    }
    jsonObject.insert(newKey, jsonObjTmp[key]);


    jsonDoc.setObject(jsonObject);

    file.resize(0); // 清空文件内容
    file.write(jsonDoc.toJson(QJsonDocument::Indented));
    file.close();
}
